package com.xz.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xz.usercenter.common.BaseResponse;
import com.xz.usercenter.common.DeleteRequest;
import com.xz.usercenter.common.ErrorCode;
import com.xz.usercenter.common.ResultUtils;
import com.xz.usercenter.exception.BusinessException;
import com.xz.usercenter.model.domain.Team;
import com.xz.usercenter.model.domain.User;
import com.xz.usercenter.model.domain.UserTeam;
import com.xz.usercenter.model.dto.TeamQuery;
import com.xz.usercenter.model.request.TeamAddRequest;
import com.xz.usercenter.model.request.TeamJoinRequest;
import com.xz.usercenter.model.request.TeamQuitRequest;
import com.xz.usercenter.model.request.TeamUpdateRequest;
import com.xz.usercenter.model.vo.TeamUserVO;
import com.xz.usercenter.service.TeamService;
import com.xz.usercenter.service.UserService;
import com.xz.usercenter.service.UserTeamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author xuzhou
 * @Description 队伍接口
 */
@Api("队伍接口")
@RestController
@RequestMapping("/team")
@Slf4j
public class TeamController {

    @Resource
    private UserService userService;

    @Resource
    private TeamService teamService;

    @Resource
    private UserTeamService userTeamService;


    /**
     * 添加队伍。
     *
     * @param teamAddRequest 添加队伍的请求体，包含队伍信息。
     * @param request        HTTP请求对象，用于获取登录用户信息。
     * @return 添加成功的队伍ID。
     */
    @ApiOperation("添加队伍")
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User logininUser = userService.getLoginUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        long teamId = teamService.addTeam(team, logininUser);
        return ResultUtils.success(teamId);
    }

    /**
     * 更新队伍信息。
     *
     * @param teamUpdateRequest 更新队伍信息的请求体，包含更新后的队伍信息。
     * @param request           HTTP请求对象，用于获取登录用户信息。
     * @return 更新操作的结果。
     */
    @ApiOperation("更新队伍信息")
    @PutMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if (teamUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User logininUser = userService.getLoginUser(request);
        boolean result = teamService.updateTeam(teamUpdateRequest, logininUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 根据ID获取队伍信息。
     *
     * @param id 队伍的ID。
     * @return 查询到的队伍信息。
     */
    @ApiOperation("根据ID获取队伍信息")
    @GetMapping("/get")
    public BaseResponse<Team> getTeamById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success(team);
    }


    /**
     * 查询队伍列表。分页查询
     *
     * @param teamQuery 查询条件对象，包含分页和过滤条件。
     * @param request   HTTP请求对象，用于获取登录用户信息和判断是否为管理员。
     * @return 查询到的队伍列表。
     */
    @ApiOperation("查询队伍列表")
    @GetMapping("/list")
    public BaseResponse<IPage<TeamUserVO>> listTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean isAdmin = userService.isAdmin(request);

        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());

        // 1、查询队伍列表
        IPage<TeamUserVO> teamList = teamService.pageTeams(teamQuery, isAdmin, page);

        final List<Long> teamIdList = teamList.getRecords().stream().map(TeamUserVO::getId).collect(Collectors.toList());
        // 2、判断当前用户是否已加入队伍
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            User loginUser = userService.getLoginUser(request);
            userTeamQueryWrapper.eq("user_id", loginUser.getId());
            userTeamQueryWrapper.in("team_id", teamIdList);
            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
            // 已加入的队伍 id 集合
            Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            teamList.getRecords().forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch (Exception e) {
            // 不做处理
            // 未登录也可以查询队伍
        }
        // 3、查询已加入队伍的人数
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("team_id", teamIdList);
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);
        // 队伍 id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.getRecords().forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
        return ResultUtils.success(teamList);
    }

    /**
     * 用户加入队伍。
     *
     * @param teamJoinRequest 加入队伍的请求体，包含队伍ID等信息。
     * @param request         HTTP请求对象，用于获取登录用户信息。
     * @return 加入操作的结果。
     */
    @ApiOperation("加入队伍")
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "加入失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 用户退出队伍。
     *
     * @param teamQuitRequest 退出队伍的请求体，包含队伍ID等信息。
     * @param request         HTTP请求对象，用于获取登录用户信息。
     * @return 退出操作的结果。
     */
    @ApiOperation("退出队伍")
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.quitTeam(teamQuitRequest, loginUser);
        return ResultUtils.success(result);
    }


    /**
     * 解散队伍
     *
     * @param deleteRequest 待解散队伍的请求体，包含队伍ID等信息。
     * @param request       HTTP请求对象，用于获取登录用户信息。
     * @return 删除操作的结果。
     */
    @ApiOperation("解散队伍")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = deleteRequest.getId();
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.deleteTeam(id, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        return ResultUtils.success(true);
    }

    /**
     * 获取当前用户创建的队伍列表
     *
     * @param teamQuery 查询条件
     * @param request   HTTP请求对象，用于获取登录用户信息。
     * @return 查询到我创建的队伍列表
     */
    @ApiOperation("获取当前用户创建的队伍列表")
    @GetMapping("/list/my/create")
    public BaseResponse<IPage<TeamUserVO>> listMyCreateTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        teamQuery.setUserId(loginUser.getId());

        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());

        IPage<TeamUserVO> teamList = teamService.pageTeams(teamQuery, true, page);
        return ResultUtils.success(teamList);
    }

    /**
     * 查询我加入的团队列表。
     * 通过团队查询条件和当前登录用户的信息，获取用户加入的团队列表。
     * 先根据登录用户ID查询用户加入的团队信息，然后根据团队ID查询团队详情及成员信息。
     *
     * @param teamQuery 团队查询条件，包含团队ID列表等信息。
     * @param request   HTTP请求对象，用于获取当前登录用户信息。
     * @return 返回包含团队详情及成员信息的响应对象。
     * @throws BusinessException 如果团队查询条件为空，则抛出业务异常。
     */
    @ApiOperation("查询我加入的队伍列表")
    @GetMapping("/list/my/join")
    public BaseResponse<IPage<TeamUserVO>> listMyJoinTeams(TeamQuery teamQuery, HttpServletRequest request) {
        // 校验团队查询条件是否为空
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取当前登录用户信息
        User loginUser = userService.getLoginUser(request);
        // 构建查询条件，查询当前用户加入的团队信息
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", loginUser.getId());
        List<UserTeam> userTeamList = userTeamService.list(queryWrapper);
        // 根据团队ID对查询结果进行分组，以便后续处理
        // 取出不重复的队伍 id
        // teamId userId
        // 1, 2
        // 1, 3
        // 2, 3
        // result
        // 1 => 2, 3
        // 2 => 3
        Map<Long, List<UserTeam>> listMap = userTeamList
                .stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));
        // 提取所有团队ID，用于进一步查询团队详情
        List<Long> idList = new ArrayList<>(listMap.keySet());
        // 设置团队查询条件中的团队ID列表
        teamQuery.setIdList(idList);

        Page<Team> page = new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize());
        // 根据更新后的团队查询条件，查询团队详情及成员信息
        IPage<TeamUserVO> teamList = teamService.pageTeams(teamQuery, true, page);
        // 返回查询结果
        return ResultUtils.success(teamList);
    }
}
